在需要切換分頁時,我們可以透過router去實現,步驟如下
輸入指令讓npm下載
npm install react-router-dom
接下來創建One.js和Two.js作為分頁範例
One.js
import React from "react";
import { Link } from "react-router-dom"; //取得react-router-dom的Link做連結用
const One = () => {
return (
<div>
<h1>List1</h1>
<Link to="/two">List2</Link> //設定目的網址
</div>
);
};
export default One;
Two.js
import React from "react";
import { Link } from "react-router-dom"; //取得react-router-dom的Link做連結用
const Two = () => {
return (
<div>
<h1>List2</h1>
<Link to="/">List1</Link> //設定目的網址,/為首頁
</div>
);
};
export default Two;
最後在App.js做設定
import One from "./One"; //取得One Component
import Two from "./Two"; //取得Two Component
import { BrowserRouter, Routes, Route } from "react-router-dom";
function App() {
return (
<div className="App">
<BrowserRouter>
<Routes>
<Route path="/" element={<One />} /> //設定One分頁的網址
<Route path="/two" element={<Two />} /> //設定Two分頁的網址
</Routes>
</BrowserRouter>
</div>
);
}
export default App;
現在兩張分頁可以任意切換了,網址也會跟著變換
【以上為我的學習心得,如有錯誤歡迎糾正】